#coding=utf-8
#LightCam DsgCompare监控程序
#init by hfh 20150707

import multiprocessing,subprocess,threading
import socket,os,time,re,traceback,sys
import lc_libs

def func(this):

	agent_hostname=this['agent_hostname']
	dbname=this['dbname']
	sqlname=this['sqlname']
	alertflag=this['alertflag']
	interval=this['interval']
	severity=this['severity']
	schedule=this['schedule']
	holiday=this['holiday']
	
	try:
		Node=agent_hostname
		AlertGroup="MonitorOracle"
		AlertKey=dbname+"-"+sqlname
		Summary=""
		Severity=severity
		Type=1
			
		sqlfile=open("../sql/"+sqlname+".sql",'r')
		sqlstr=sqlfile.read()
		#res=db.executesql(sqlstr)
		#comd="/oracle/product/11.2/bin/sqlplus -s cffex/biz_pwd_0522@%s @/monitor/LightCam/sql/dsgcompare.sql" % dbname
		comd="/oracle/product/11.2/bin/sqlplus -s cffex/biz_pass_0908@%s @/monitor/LightCam/sql/dsgcompare.sql" % dbname
		popen=subprocess.Popen(comd,stdout=subprocess.PIPE,stderr=subprocess.PIPE,shell=True)
		res=popen.stdout.read().strip("\n").strip("\r")
		if res == None:
			print "no result"
			return 0
		else:
			#print res
			pass
			
		if sqlname == 'dsgcompare':
			if '__StartOfLine__' in res:
				pass
			else:
				print "nothing to do ,exiting"
				return 0
			for lines in res.split('__StartOfLine__'):
				if "__EndOfLine__" in lines:
					line=lines.split("__EndOfLine__")[0].split(',')
					items=[]
					for item in line:
						try:
							item=item.decode('gbk').encode('utf8')
						except:
							pass
						items.append(item.strip(' \t'))
						
					#Summary="DSG数据比对报错，SOURCE:%s0,DATE:%s1,DBLINKNAME:%s2,SCHEMA_NAME:%s3,TABLE_NAME:%s4,REMARK:%s5" % (items[0],items[1],items[2],items[3],items[4],items[5])
					Summary="DSG数据比对报错(%s),%s.%s@%s,%s" % (items[1],items[3],items[4],items[2],items[5])
					AlertGroup="OraDsgCompare"
					AlertKey="%s-%s-%s-%s-%s" % (items[0],items[1],items[2],items[3],items[4])

					#初始化标志文件
					alertfilename=lchome+"/alert/lc_dsgcompare_"+AlertKey
					
					try:
						fc=open(alertfilename,'r+')
						flag=fc.read().strip('\n\r')
						fc.close()
						#if flag=='0':
						#	fc=open(alertfilename,'w')
						#	fc.write('1')
						#	fc.close()
						#	strs=lc_libs.lc_gen_alert(agent_hostname,Node,AlertGroup,AlertKey,Severity,Type,Summary)
						#	print strs
						#	lc_libs.lc_alert(strs)
					except IOError:
						fc=open(alertfilename,'w')
						fc.write('1')
						fc.close()
						strs=lc_libs.lc_gen_alert(agent_hostname,Node,AlertGroup,AlertKey,Severity,Type,Summary)
						print strs
						lc_libs.lc_alert(strs)

	except Exception:
		excinfo=traceback.format_exc()
		print excinfo
		logdate=time.strftime('%b %d %H:%M:%S',time.localtime())
		logfile.write(logdate+" :\n"+excinfo+"\n")
		logfile.flush()
		time.sleep(1)


if __name__ == "__main__":


	cmd='echo $LIGHTCAM_HOME'
	popen=subprocess.Popen(cmd,stdin=subprocess.PIPE,stdout=subprocess.PIPE,stderr=subprocess.PIPE,shell=True)
	while True:
		if popen.poll()==None:
			time.sleep(0.1)
			continue
		else:
			break
	lchome=popen.stdout.read().strip('\r\n')
	scname=sys.argv[0].split('.')[0]
	logfilename=lchome+'/log/'+scname+'.log'
	confname=lchome+'/conf/'+scname+'.conf'
	logfile=file(logfilename,'a')
	logdate=time.strftime('%Y-%m-%d %H:%M:%S',time.localtime())
	logfile.write(logdate+" Started.\n")
	logfile.flush()
	
	agent_hostname=lc_libs.lc_gethostname()
	
	#pool = multiprocessing.Pool(processes=1)
	#result = []

	#初始化Oracle数据库
	cmd='which sqlplus'
	popen=subprocess.Popen(cmd,stdin=subprocess.PIPE,stdout=subprocess.PIPE,stderr=subprocess.PIPE,shell=True)
	while True:
		if popen.poll()==None:
			time.sleep(0.1)
			continue
		else:
			break
	sqlcmd=popen.stdout.read().strip('\r\n')
	
	#sqlcmd="/oracle/product/11.2.0/mondb/bin/sqlplus"
	#host="127.0.0.1"
	#host="172.22.240.41"
	#port="1521"
	#sid="orabiz"
	#username="cffex"
	#password="biz_pwd_0522"
	#
	#db=lc_libs.lc_oracledb_operater(sqlcmd,host,port,sid,username,password)


	#主程序
	MonitorList = []
	
	for lines in open(confname):
		if lines[0] == '#' or lines.split("\t")[0] not in (agent_hostname,'default'):
			continue

		line=lines.strip('\r\n').split('\t')
		dconf={}
		
		dconf['agent_hostname']=line[0]
		dconf['dbname']=line[1]
		dconf['sqlname']=line[2]
		dconf['alertflag']=line[3]
		dconf['interval']=line[4]
		dconf['severity']=line[5]
		dconf['schedule']=line[6]
		dconf['holiday']=line[7]
	
		MonitorList.append(dconf)

	usedtime=0
	
	while True:
		time.sleep(1)
		realtime=int(time.time())
		
		logdate=time.strftime('%Y-%m-%d %H:%M:%S',time.localtime())
		holiday_state = lc_libs.lc_isholiday()
		
		threads = []
		for i in MonitorList:
			if int(i['holiday']) == 1 and holiday_state == True:
				continue
				
			time_state = lc_libs.lc_schedule(i['schedule'])
			if time_state == False:
				continue
			
			flag=realtime%int(i['interval'])
			#print flag
			if flag<=usedtime:
				#print i
				t = threading.Thread(target=func,args=(i,))
				threads.append(t)
		
		for t in threads:
			t.start()
			while True:
				#print len(threading.enumerate())
				time.sleep(0.01)
				if(len(threading.enumerate()) < 100):
					break

		#排除执行程序导致的时间差
		usedtime=int(time.time())-realtime
		#print "usedtime:%s" % usedtime
